package com.flame.core.utils.cipher;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * RsaCipher
 *
 * @author wuxintong
 * @since 2023/1/28
 */
public class RsaCipher implements FlameCipher {

    private static final String PUBLIC_KEY =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUevTU1bpnq1RSMQIliMfkSS0gqvJTzu7n0HPvIbfyuTmiS8qBVmB2w7pvv5UqCN0wbLhF8xtyzXdUfEXAQUpylwMuQ0u4CJVRANxHlJDQCN5BvNC99OcYrvlqEWUw+Xlr4824uGpSz22AKg1ni0Nh6o/72g3W3F3XV88QFzv73wIDAQAB";

    private static final String PRIVATE_KEY =
        "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJR69NTVumerVFIxAiWIx+RJLSCq8lPO7ufQc+8ht/K5OaJLyoFWYHbDum" +
            "+/lSoI3TBsuEXzG3LNd1R8RcBBSnKXAy5DS7gIlVEA3EeUkNAI3kG80L305xiu+WoRZTD5eWvjzbi4alLPbYAqDWeLQ2Hqj" +
            "/vaDdbcXddXzxAXO/vfAgMBAAECgYB9TjcI10Z07vY" +
            "+VvXEz2ZCli7rftj7OYwNPrJYgVBIG2E0QlooRMkr8YqJfFlaHBjvIRFylvP3MsceGbKTyYYVXVwO0GtF" +
            "+egXIdlzY7SSSVyDxd7PzCBxsBYKXD2WplmPmfZ7FkPpGTtolJxFzeu8L2TG090" +
            "/57o6kiXKF7pkwQJBAMsNkhFW9496lLOP1Qe5b61UZjEeYeJDu84291AlSCcZ9MQZNJxB26wsbynbAKPKVrQ5kLwFUoryhUUJz3lo" +
            "+bcCQQC7MnwpsF3gvTILkcdN36ljaafXmB3srqqxJDsEA19HH9cpKAqrgIE5CxtU7w21riI2F6mZzWawuNSGVhvW9S8ZAkARwZ8LWyKM7nhAd4x2f3XPn3jMRM7kfW3X66CW5pu3p6Jq35VlMLEoDj6uV1Nn/1KzsfEBMCn2spyK2//DqzVjAkBbmEk+kMhuhcRt+sd9aBnWxcTVbd3+iDyG7oZd4VSGVaMOxUPrRLZ19eRKu6mGowykURGwatt7TwTWMl3u4QtJAkEAySjKub7hE9zU9Lm2YlsKkFooRdxIQ3zYasWU1wAM3GdCYqbUN/BNzHEUXsbMBytD3/d7H8JLp8/VHKKCIku7Jg==";

    public Map<String, String> generateKey() {
        Map<String, String> map = new HashMap<>();
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            // 512、1024、2048
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

            map.put("publicKey", publicKey);
            map.put("privateKey", privateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public String encrypt(String data, String publicKey) throws Exception {
        byte[] decodedPublicKey = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decodedPublicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] res = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(res);
    }

    @Override
    public String decrypt(String data, String privateKey) throws Exception {
        byte[] decodedPrivateKey = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] dataBytes = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        byte[] res = cipher.doFinal(dataBytes);
        return new String(res, StandardCharsets.UTF_8);
    }

    @Override
    public String encrypt(String data) throws Exception {
        return encrypt(data, PUBLIC_KEY);
    }

    @Override
    public String decrypt(String data) throws Exception {
        return decrypt(data, PRIVATE_KEY);
    }
}
